<script setup lang="ts">
import type { MenuButtonOption, MenuResp } from '#/api/system/menu/model';

import { computed, nextTick, ref } from 'vue';

import { useVbenDrawer } from '@vben/common-ui';
import { $t } from '@vben/locales';
import { cloneDeep, eachTree } from '@vben/utils';

import { useVbenForm } from '#/adapter/form';
import { roleMenuTreeSelect } from '#/api/system/menu';
import { roleSavePermission } from '#/api/system/role';
import { MenuSelectTable } from '#/components/tree';
import { defaultFormValueGetter, useBeforeCloseDiff } from '#/utils/popup';

import { authDrawerSchemas } from './data';

const emit = defineEmits<{ reload: [] }>();

const id = ref<number>();
const title = computed(() => {
  return id.value ? $t('pages.common.edit') : $t('pages.common.add');
});

const [BasicForm, formApi] = useVbenForm({
  commonConfig: {
    componentProps: {
      allowClear: true,
      class: 'w-full',
    },
    formItemClass: 'col-span-1',
  },
  layout: 'vertical',
  schema: authDrawerSchemas(),
  showDefaultActions: false,
  wrapperClass: 'grid-cols-1 gap-x-4',
});

const menuTree = ref<MenuResp>({
  menuVoList: [],
  resourceVoList: [],
});
async function setupMenuTree(id?: number) {
  if (id) {
    const resp = await roleMenuTreeSelect(id);
    // keys依赖于menu 需要先加载menu
    // 获取所有checked=true的菜单
    const checkedMenus: number[] = [];
    eachTree(resp.menuVoList, (node) => {
      node.children = node.childMenuList;
      if (node.checked) {
        checkedMenus.push(node.id);
      }
    });
    // 设置菜单信息
    menuTree.value = resp;
    const checkedButtons: number[] = [];
    const menuButtonOptions = resp.resourceVoList.map(
      (item: MenuButtonOption) => {
        if (item.checked) {
          checkedButtons.push(item.id);
        }
        return {
          label: item.resourceName,
          value: item.id,
        };
      },
    );
    formApi.updateSchema([
      {
        componentProps: {
          options: menuButtonOptions,
        },
        fieldName: 'resourceIdList',
      },
    ]);
    await nextTick();
    await formApi.setValues({
      menuIdList: checkedMenus,
      resourceIdList: checkedButtons,
    });
  }
}

async function customFormValueGetter() {
  const v = await defaultFormValueGetter(formApi)();
  // 获取勾选信息
  const menuIdList = menuSelectRef.value?.getCheckedKeys?.() ?? [];
  const mixStr = v + menuIdList.join(',');
  return mixStr;
}

const { onBeforeClose, markInitialized, resetInitialized } = useBeforeCloseDiff(
  {
    initializedGetter: customFormValueGetter,
    currentGetter: customFormValueGetter,
  },
);

const [BasicDrawer, drawerApi] = useVbenDrawer({
  class: 'w-[500px]',
  onBeforeClose,
  onClosed: handleClosed,
  onConfirm: handleConfirm,
  destroyOnClose: true,
  async onOpenChange(isOpen) {
    if (!isOpen) {
      return null;
    }
    drawerApi.drawerLoading(true);

    const { id: idValue } = drawerApi.getData();
    id.value = idValue;

    // init菜单 注意顺序要放在赋值record之后 内部watch会依赖record
    await setupMenuTree(idValue);
    await markInitialized();

    drawerApi.drawerLoading(false);
  },
});

const menuSelectRef = ref<InstanceType<typeof MenuSelectTable>>();
async function handleConfirm() {
  try {
    drawerApi.lock(true);

    const { valid } = await formApi.validate();
    if (!valid) {
      return;
    }
    // 这个用于提交
    const menuIdList = menuSelectRef.value?.getCheckedKeys?.() ?? [];
    // formApi.getValues拿到的是一个readonly对象，不能直接修改，需要cloneDeep
    const data = cloneDeep(await formApi.getValues());
    data.menuIdList = menuIdList;
    await roleSavePermission({
      roleId: id.value,
      ...data,
    });
    emit('reload');
    resetInitialized();
    drawerApi.close();
  } catch (error) {
    console.error(error);
  } finally {
    drawerApi.lock(false);
  }
}

async function handleClosed() {
  await formApi.resetForm();
  resetInitialized();
}
</script>

<template>
  <BasicDrawer :title="title">
    <BasicForm>
      <template #menuIdList="slotProps">
        <div class="h-[600px] w-full">
          <MenuSelectTable
            ref="menuSelectRef"
            :checked-keys="slotProps.value"
            :menus="menuTree"
          />
        </div>
      </template>
    </BasicForm>
  </BasicDrawer>
</template>
